package com.cszjzx.member.service;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

import com.cszjzx.member.dao.*;
import com.cszjzx.member.po.*;

public class DepartmentServiceImpl implements DepartmentService {
	
	private DepartmentDAO departmentDAO ;
	private MemberDAO memberDAO;
	
	public DepartmentServiceImpl() {
		try{
			departmentDAO = new DepartmentDAOImpl();
			memberDAO = new MemberDAOImpl();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	@Override
	public List<Department> getDepartments() {
		
		List<Department> list = null;
		try {
			list = departmentDAO.findAll();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public boolean addDepartment(String name) {
		
		Department department = new Department(name);
		try {
			departmentDAO.add(department);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean deleteDepartments(int id) {
		
		try {
				departmentDAO.delete(id);
		} catch (SQLException e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public List<Department> getDepartmentsByProcess(String process, int masterDepId) {
		
		List<Department> list = null;
		try {
			//超级管理员
			if(masterDepId == 0){
				list = departmentDAO.findAll();
				for(int i=0;i<list.size();i++){
					list.get(i).setNums(0);
				}
				//找出该阶段的所有学生
				List<Member> members = memberDAO.find("process", process);
				for(int i=0;i<members.size();i++){
					String d = members.get(i).getValue("department");
					for(int j=0;j<list.size();j++){
//						if(list.get(i).getId())
						if(list.get(j).getName().equals(d)){
							list.get(j).setNums(list.get(j).getNums()+1);
						}
					}
				}
			}
			//管理员
			else{
				list = departmentDAO.findAll();
				Department dept = null;
				for(int i=0;i<list.size();i++){
					if(list.get(i).getId() == masterDepId){
						dept = list.get(i);
					}
				}
				list = new ArrayList<Department>();
				list.add(dept);
				//找出该阶段该系的所有学生
				List<Member> members = memberDAO.find("process", process);
				for(int i=0;i<members.size();i++){
					String d = members.get(i).getValue("department");
					if(list.get(0).getName().equals(d)){
						list.get(0).setNums(list.get(0).getNums()+1);
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
}
